#!/usr/bin/env python
#=======================================================================
#
#          FILE: ifconfig.py
#         USAGE: ./ifconfig.py
#   DESCRIPTION: Enhanced ifconfig
#  REQUIREMENTS: ethtool
#          BUGS: N/A
#         NOTES: N/A
#        AUTHOR: Ali Ayoub
#         EMAIL: ali@mellanox.com
#       COMPANY: N/A
#       CREATED: 09.17.2010-15:56:16
#      REVISION: 2.0
#=======================================================================

import os
import sys

def dev_link(dev):
	link   = os.popen("ethtool %s    | grep detected    | awk '{print $3}'" % dev).read().strip()
	if not len(link): # ipoib does not support ethtool link detection
		link = os.popen("cat /sys/class/net/%s/carrier 2> /dev/null" % dev).read().strip()
		if  link == "1":
			link = "yes"
		elif link  == "0":
			link = "no"
		else:
			link = "NA"
	if not len(link) or link == "NA":
		link = os.popen("ifconfig %s 2> /dev/null | grep RUNNING" % dev).read().strip()
		if link == "":
			link = "no"
		else:
			link = "yes"
	return link
		
if os.geteuid() != 0:
	print "-E- you must be root to run this script."
	sys.exit(1)
devices = os.popen("ifconfig -a 2> /dev/null | grep encap | awk '{print $1}'").read().strip().split("\n")

for dev in devices:
	if dev == "lo" or dev == "sit0" : continue
	if os.system("ethtool -i %s &> /dev/null" % dev):
		print "[%6s]: %10s" % (dev, "NA")
		continue
	driver = os.popen("ethtool -i %s | grep driver      | awk '{print $2}'" % dev).read().strip()
	link   = dev_link(dev)
	mac    = os.popen("ifconfig %s 2> /dev/null | grep HWaddr      | awk '{print $5}'" % dev).read().strip()
	ip     = os.popen("ifconfig %s 2> /dev/null | grep 'inet addr' | awk '{print $2}' | cut -d:   -f2" % dev).read().strip()
	mask   = os.popen("ifconfig %s 2> /dev/null | grep 'Mask'      | awk '{print $4}' | cut -d:   -f2" % dev).read().strip()
	mtu    = os.popen("ifconfig %s 2> /dev/null | grep 'MTU'       | cut -d: -f2      | cut -d' ' -f1" % dev).read().strip()
	print "[%12s]: %10s, link %4s, IP %12s netmask %12s mtu %6s" % (dev, driver, link, ip, mask, mtu)

sys.exit(0)

